home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 5967 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.6 KB  |  63 lines

  1. Path: news.magg.net!news
  2. From: n4mwd@magg.net (Dennis Hawkins)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Why does this work?
  5. Date: Thu, 22 Feb 1996 05:46:35 GMT
  6. Organization: M.A.G. Information Services (MAGG.NET)
  7. Message-ID: <4ggsi6$1fg@dopey.magg.net>
  8. References: <4g8f7o$adt@ncar.ucar.edu>
  9. NNTP-Posting-Host: wpb-133.magg.net
  10. X-Newsreader: Forte Free Agent 1.0.82
  11.  
  12. rosinski@ra.cgd.ucar.edu (Jim Rosinski) wrote:
  13.  
  14. >Could someone please explain why the following code works?  In particular, I
  15. >am perplexed as to why "sub1" and "sub2" declared as elements of "cmndtable"
  16.  
  17. >#include <stdio.h>
  18. >main()
  19. >{
  20. >  void sub1(), sub2();
  21.  
  22. >  struct cmndstruct {
  23. >    void (*funcnam)();
  24. >  };
  25.  
  26. >  struct cmndstruct cmndtable[] = {
  27. >    sub1,
  28. >    sub2,
  29. >    NULL
  30. >  };
  31. >  struct cmndstruct *cmndptr;
  32.  
  33. >  for (cmndptr = cmndtable; *(cmndptr->funcnam) != NULL; cmndptr++) {
  34. >    (*(cmndptr->funcnam))();
  35. >  }
  36. >  exit(0);
  37. >}
  38.  
  39. >void sub1()
  40. >{
  41. >  printf("Inside sub1\n");
  42. >}
  43.  
  44. >void sub2()
  45. >{
  46. >  printf("Inside sub2\n");
  47. >}
  48.  
  49. There is nothing really all that unusual about your program.  The only
  50. thing that looks a little strange to me was that you have a structure
  51. with only one field in it.  A simple array of pointers to functions
  52. would be more efficient.  As far as the machine knows, that is
  53. precisely what you have here.  I would reccommend that you consider
  54. spicing it up a bit by using pointers to functions that take
  55. parameters.  Your code here is straightforward.  You initialize your
  56. pointers to functions and then you call them one after the other in a
  57. for() loop.  No sweat.
  58.  
  59.  
  60. Dennis Hawkins
  61. n4mwd@amsat.org
  62.  
  63.